<template lang="jade">
div.return-bar
	i.iconfont(@click="back()") &#xe668;
	自动投标
div.user-auto.detail_top
	div.auto_buy
		dialog(:show.sync="auto_buy_dialog")

			div.autobuy
				b 请输入手机验证码：
				div(style="vertical-align:middle")
					input(type="text", v-model="returnSMS.OTPNO", style="vertical-align:middle")
					button( style="vertical-align:middle",  @click="sentSMS")
						{{ msn.btnTxt }}
				div
					button(@click="stopAutoBuy") 提交
			i.iconfont(@click="close_auto") &#xe629;

	dl.com
		dt 投标状态
		dd
			span.title 自动投标
			span.content
				span.status {{status_txt}}
				input(type="checkbox", class="chk_3",  id="checkbox1", v-bind:checked = " schecked == 1 ",   disabled)
				label(for="checkbox1", @click="showAutoWarning()")

		dd(v-link="{ path: '/auto-buy-ranking/'}")
			span.title 当前排名
			span.content
				i.iconfont.go &#xe600;
				div.hl {{sort}}名

	dl.com
		dt 投标设置
		dd(v-link="{ path: '/auto-buy-sub/2'}")
			span.title 投标期限
			span.content
				i.iconfont.go &#xe600;
				div {{period}}
		dd(v-link="{ path: '/auto-buy-sub/3'}")
			span.title 投标金额
			span.content
				i.iconfont.go &#xe600;
				div {{money}}
		dd(v-link="{ path: '/auto-buy-sub/4'}")
			span.title 投标项目
			span.content
				i.iconfont.go &#xe600;
				div {{borrow_type}}


		dd(v-link="{ path: '/auto-buy-sub/5'}")
			span.title 保留金额
			span.content
				i.iconfont.go &#xe600;
				div {{retain_min_money}}


form-page(:url.sync="post_url", :rdata.sync="post_data")
com-alert(:show.sync="alertData.show", :title.sync="alertData.title", :buttontxt.sync="alertData.buttontxt", :content.sync="alertData.content")

div.homeloading
	loading(:show="show_loading", text="正在加载")

confirm(:show.sync="showAutoTerms", title="温馨提醒", confirm-text="确认", cancel-text="再看看", @on-cancel = "onCancelAuto()", @on-confirm="setAuto")
	auto-terms

</template>

<script>
var time_work = null;
import '../../assets/sass/user/auto-buy.scss'
import '../../assets/sass/common/dialog.scss'
//import DialogPage from '../../components/common/dialog'
import {Api_Get_AutoBuy, Api_Set_Auto, Api_Send_Auto_SMS, Api_Send_Set_Auto_Buy} from '../../config/api'
import {Loading, Dialog, XButton, Confirm} from 'vux'
import api from '../../data/api';
import FormPage from '../../components/common/form'
import ComAlert from '../../components/common/alert'
import AutoTerms from '../../components/auto_terms';

import { mapGetters, mapActions } from 'vuex'

export default{
	data(){
		return {

			showAutoTerms:false,
            alertData:{
                show:false,
                title:'标题',
                buttontxt:'确定',
                content:'sign'
            },

			post_url: '',
			post_data:{},
			show_dialog:false,
			busy:false,
			subForm:null,
			auto_buy_dialog:false,
			msg:'<div class="autobuy"><b>自动投标关闭功能只能用PC版完成</b><br>移动版暂时只支持开启或参数设定<br>谢谢合作!</div>',
			showDialog: false,

			/* code_msg:'重新发送',
			code_msg_btn:false, */
			msn:{
				stop:false,
				disableBtn:false,
				btnTxt:"重新发送",
				timer:0
			},

			returnSMS:{
				OTPSEQNO: '',
				OTPNO: '',
				status: false
			},

			min_money:'',
			max_money:'',

			min_period:'',
			max_period:'',
			period:'',
			money:'',
			borrow_type:'',
			retain_min_money:'',
			status_txt:'',
			schecked:'',
			ranking:'',
			sort:'',
			autoRs:{
				status:false
			}
		}
	},
	components:{
		AutoTerms,
		Confirm,
		ComAlert,
  		FormPage,
	  	Loading,
		Dialog,
		XButton
	},


    computed: {
		...mapGetters([
            'showLoading'
        ])
    },

	methods: {
        ...mapActions([ 'setShowLoading' ]),

		getForm(){
		  for(var a in this.$children){
			if(this.$children[a].name == 'form')
			  this.subForm = this.$children[a];
		  }
		},
	  	close_auto(){
	  		this.auto_buy_dialog = !this.auto_buy_dialog;
	  	},
		back(){
			this.$route.router.go('/user')
		},
		show(){
			this.$children[0].show = true
		},
		hide(){
			this.$children[0].show = false;
		},


		sendAutoConfirmSMS(){
			var data = {};
			if(this.busy){
				return;
			}
			this.busy = true;
			//this.$store.dispatch('setShowLoading', true);
			this.$http.post(Api_Send_Auto_SMS, data,'').then(function (response) {
				var obj = response.data;
				//this.$store.dispatch('setShowLoading', false);
				this.busy = false;
				if(!obj.status){
					//alert(obj.msg);
					this.alertData = {show:true, title:'信息提示', buttontxt:'确定', content:obj.msg};
					this.stopTimeCount();
				}else{
					this.returnSMS.OTPSEQNO = obj.OTPSEQNO;
					this.returnSMS.status = obj.status;
				}
			});
		},

		//关闭自动投标
		stopAutoBuy(){

			console.log( this.returnSMS.OTPNO =='' )
			//return;
			if(this.returnSMS.status == false || this.busy == true || this.returnSMS.OTPNO =='' ){
				return;
			}else{
				this.busy = true;
				this.$store.dispatch('setShowLoading', true);
				var data = {
					OTPSEQNO: this.returnSMS.OTPSEQNO,
					OTPNO: this.returnSMS.OTPNO
				};
				this.$http.post(Api_Send_Set_Auto_Buy, data,'').then(function (response) {
					var obj = response.data;
					this.$store.dispatch('setShowLoading', false);
					//alert(obj.msg);
					this.alertData = {show:true, title:'信息提示', buttontxt:'确定', content:obj.msg};
					this.busy = false;
					//this.stopTimeCount();

					if(obj.status){
						this.auto_buy_dialog = false
						this.schecked  = "0";
					}

				});

			}

		},

	    updateSms () {

	    	console.log('get ')
	        if(this.msn.timer <= 0)
	        {
				this.stopTimeCount();
	        }
	        else{
	            this.msn.timer--;
	            this.msn.btnTxt = '剩余'+this.msn.timer+'秒';
	        }

	    },

		stopTimeCount(){
			clearInterval(time_work);
			this.msn.timer  = 0;
			this.msn.stop = false;
			this.msn.disableBtn = false;
			this.msn.btnTxt = "重新发送";
		},
	    startTimer () {
			clearInterval(time_work);
			//if(this.msn.timer>0) return;
			if(this.msn.timer == 0)	this.msn.timer = 60;
	        if(this.msn.stop == false)
	        {
				time_work = setInterval(this.updateSms,1000);
	        }
	        else
	        {
				clearInterval(time_work);
	        }

	        //this.msn.stop = !this.msn.stop;
		},

		sentSMS(){
			if(this.msn.disableBtn){
				return;
			}
			console.log('sentSMS');
			this.msn.disableBtn = true, this.startTimer();
			this.sendAutoConfirmSMS();
		},


		async setAuto(){
			var that = this;
			if(this.schecked=="0"){

				console.log('开通自动投标!')
				this.$store.dispatch('setShowLoading', true);
				this.busy = true;
				var data = {};

				var rs = await api.user.set_auto_buy();
				if(!rs.status){
					//alert(rs.msg)
					this.alertData = {show:true, title:'信息提示', buttontxt:'确定', content:rs.msg};
					this.busy = false;
					setTimeout(() => {
						that.$route.router.go('/user')
					}, 2000);
				}else{
					this.getForm();
					this.subForm.show = true
					this.post_url = rs.action_url
					this.post_data.RequestData = rs.RequestData
					this.post_data.transCode = rs.transCode
					this.subForm.submit();
				}
			}
			else{
				console.log('关闭自动投标!')
				this.msn.disableBtn = true, this.startTimer(), this.auto_buy_dialog = true;
				if(this.msn.timer > 0 && this.msn.timer < 60 ) return;

				this.sendAutoConfirmSMS();
			}
		},

		async showAutoWarning(){

			//this.autoRs = await api.user.get_auto_buy();  //获取自动投标的设置

			if(this.autoRs.status == false || this.autoRs.data.status == '0'){
				this.schecked = "0";
				this.showAutoTerms = true;  //如果没有开通，弹出窗口，让它开通。
			}else{
				//this.fetch();  //如果有，进行配置
				//this.schecked = "1";
				this.setAuto();
			}
		},

		onCancelAuto(){
			this.showAutoTerms = false;
			this.$route.router.go('/user');
		},

		async fetch(){

			var that = this, rs = {};

			this.autoRs = await api.user.get_auto_buy();  //获取自动投标的设置
			//this.autoRs = {"data":{"id":"2","user_id":"4832","status":"1","min_period":"0","max_period":"0","max_money":"10000000.00","min_money":"10000000.00","min_apr":"12.00","max_apr":"12.00","borrow_type":"0","open_time":"1476322015","last_tender_time":"1526900839","period":"4","retain_min_money":"0.00","bank_star":"1526832000","bank_end":"1526832000","bank_money":"1000.00","tender_money":"0.00","money":"1"},"sort":"0","status":true}
			//this.autoRs ={"data":{"id":"2","user_id":"4832","status":"1","min_period":"0","max_period":"0","max_money":"10000000.00","min_money":"10000000.00","min_apr":"12.00","max_apr":"12.00","borrow_type":"0","open_time":"1476322015","last_tender_time":"1527073792","period":"4","retain_min_money":"0.00","bank_star":"1527004800","bank_end":"1527004800","bank_money":"1000.00","tender_money":"0.00","money":"1"},"sort":151,"status":true}

			//var rs = await api.user.get_auto_buy();  //获取自动投标的设置
			if(this.autoRs.status == false || this.autoRs.data.status == '0'){
				//rs = await api.user.set_auto_buy();
				//this.schecked = "0";
				//this.setAuto();
			}else{
				rs = this.autoRs;
				that.max_money = rs.data.max_money + '元'
				that.min_money = rs.data.min_money + ' 至 '

				//that.min_period = rs.data.min_period + '个月 至'
				//that.max_period = rs.data.max_period + '个月'
				var rd = rs.data.period || '', rval = "", rd = rd.split(',');

				if(rd.length ==5 ){
					that.period = "不限"
				}else{

					for(var i in rd){

						switch(rd[i]){
							case "0":
								rval = "不限"
								break;
							case "1":
								rval = "4-6个月"
								break;
							case "2":
								rval = "7-12个月"
								break;
							case "3":
								rval = "13-24个月"
								break;
							case "4":
								rval = "25-36个月"
								break;
							case "5":
								rval = "1-3个月"
								break;
						}

						if(that.period!="")
							that.period += ','+rval
						else
							that.period = rval
					}
					console.log(that.period)
				}



				switch(rs.data.money){
					case "0":
						that.money = "不限"
						break;
					case "1":
						that.money = that.min_money + that.max_money;
						break;
				}

				that.status_txt = rs.data.status == "1" ? "开启" : "关闭"
				that.schecked  = rs.data.status
				that.sort  = rs.sort;
				that.retain_min_money  = rs.data.retain_min_money;

				switch(rs.data.borrow_type){
					case "0":
						that.borrow_type = "不限"
						break
					case "1":
						that.borrow_type = "房贷"
						break
					case "2":
						that.borrow_type = "车贷"
						break
				}
			}
		}

	},

	watch : {
		'$route' (to, from) {
			// from 对象中要 router 来源信息.
			// do your want

			console.log(from.path);
		}
	},

	route:{
		activate( transition ){
			var that = this;
			if(transition.from.path!='/user'){
				//console.log('why')
				that.setShowLoading(true);
				setTimeout(() => {
					that.setShowLoading(false);
					transition.next();
					that.fetch()
				}, 3000);
			}else{
				transition.next();
				this.fetch()
			}

		}
	}
}

</script>
